//
//  ZYComposePictureView.swift
//  weiboZY
//
//  Created by 赵勇 on 16/5/20.
//  Copyright © 2016年 赵勇. All rights reserved.
//

import UIKit
//  重用标记
private let ZYComposePictureViewCellIdentifier = "ZYComposePictureViewCellIdentifier"
class ZYComposePictureView: UICollectionView, UICollectionViewDataSource, UICollectionViewDelegate {
    
    // 加号按钮添加图片的闭包
    var addImageClosure:(()->())?
    
    
    lazy var images: [UIImage] = [UIImage]()

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        registerClass(ZYComposePictureViewCell.self, forCellWithReuseIdentifier: ZYComposePictureViewCellIdentifier)
        
        dataSource = self
        
        delegate = self
//        backgroundColor = RandomColor()
        
    }
    
    func addImage(image: UIImage) {
        
        hidden = false
        
        images.append(image)

        reloadData()
    }
    
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let itemMargin: CGFloat = 5
        
        let itemWidth = (frame.size.width - 2 * itemMargin) / 3
        
        // 获取layout
        let flowLayout = self.collectionViewLayout as? UICollectionViewFlowLayout
        
        flowLayout?.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        // 间距
        flowLayout?.minimumInteritemSpacing = itemMargin
        flowLayout?.minimumLineSpacing = itemMargin
        
        
    }
    
      //  MARK:   -UICollectionViewDataSource 代理方法
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let count =  images.count
        if count == 0 || count == 9 {
            return count
        } else {
            return count + 1
        }
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ZYComposePictureViewCellIdentifier, forIndexPath: indexPath) as! ZYComposePictureViewCell
//        cell.backgroundColor = RandomColor()
        if indexPath.item < images.count {
            
            cell.image = images[indexPath.row]

        } else {
            
            cell.image = nil
        }
        
        // 设置cell删除按钮的闭包
        cell.deleteButtonClosure = { [weak self] in
         
            self?.images.removeAtIndex(indexPath.row)
            
            if self?.images.count == 0 {
                self?.hidden = true
            }
            
            self?.reloadData()
        }
        
        return cell
        
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        // 取消选中状态
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        
        if indexPath.row == images.count {
            addImageClosure?()
        }
        
    }
    
    
}




class ZYComposePictureViewCell: UICollectionViewCell {
    //  点击删除图片按钮的闭包
    var deleteButtonClosure: (()->())?
    
    // cell显示图片
    private lazy var imageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
    
    // 删除图片按钮
    private lazy var deleteImageBtn:UIButton = {
       let btn = UIButton()
        btn.setImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        btn.addTarget(self, action: "deleteImageBtnClick", forControlEvents: .TouchUpInside)
        return btn
    }()
    
    var image: UIImage? {
        
        didSet{
            
            if image == nil {
                // 隐藏删除按钮
                deleteImageBtn.hidden = true
                imageView.image = UIImage(named: "compose_pic_add")
                // 设置高亮图片
                imageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                
                
            } else {
                // 显示删除按钮
                deleteImageBtn.hidden = false
                
                imageView.image = image
             
            }
            
        }
       
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        contentView.addSubview(imageView)
        contentView.addSubview(deleteImageBtn)

        // 设置约束
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        
        deleteImageBtn.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(imageView)
            make.trailing.equalTo(imageView)
        }
    }
    
    @objc private func deleteImageBtnClick() {
        
        deleteButtonClosure?()
    }
    
}














